﻿using MetroDataApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;


namespace MetroDataApi.Controllers
{
    public class MonitorPointsGroupController : ApiController
    {
        public string Post([FromBody]string value)
        {
            if (value == null)
            {
                return JsonConvert.SerializeObject(new { success = 0, err = "post参数不能为空,检查你的post方法" });
            }
            try
            {
                JObject jsonData = JObject.Parse(value);
                var names = jsonData["names"].ToString().Split(',');
                var values = jsonData["values"].ToString().Split(',').ToList().Select(p => p == "" ? double.NaN : Convert.ToDouble(p)).ToArray();
                var prjId = jsonData["prjId"].ToObject<int>();
                var time = jsonData["time"].ToString();

                if (names.Length != values.Length)
                {
                    return JsonConvert.SerializeObject(new { success = 0, err = "values和names参数包含的数据个数不一致." });
                }


                var result = "";
                var noDuplicateResults = names.Zip(values, (t, v) => new result
                {
                    name = t,
                    value = v,
                    time = time
                }).GroupBy(p => p.name).Select(t => new result()
                {
                    name = t.Key,
                    value = t.First().value,
                    time = time
                });

                var reviews = new List<bool>();

                foreach (var p in noDuplicateResults)
                {
                    if (!double.IsNaN(p.value))
                    {
                        var review = false;
                        var tempRe = UploadMonitorPointsHelper.UploadPreCheck(prjId, p, out review);
                        reviews.Add(review);
                        if (tempRe.Length > 0)
                        {
                            result += tempRe + "\r\n";
                        }
                    }
                    else
                    {
                        result += p.name + "数值不能为非数字" + "\r\n";
                    }
                }
                //录入数据库
                MetroDataQuery.Utility.UpdateMonitorPointQuery.UpdatePoints(prjId, time, names, values, reviews.ToArray());

                if (noDuplicateResults.Count() > 0 && reviews[0])
                {
                    UploadMonitorPointsHelper.PublishReviewEventToRedis(prjId, time);
                }

                return JsonConvert.SerializeObject(new { success = result.Length > 0 ? 0 : 1, err = result });
            }
            catch (Exception a)
            {
                return JsonConvert.SerializeObject(new { success = 0, err = a.Message });
            }
        }
    }
}
